<html>

<head>
    <script type="text/javascript">
        function say() {
            alert("parent.html");
        }
        function callChild() {
            myFrame.window.say();
            myFrame.window.document.getElementById("button").value = "调用结束";
        }
    </script>
</head>

<body>
    <input id="button" type="button" value="调用child.html中的函数say()" onclick="callChild()" />
    <input id="button" type="button" value="打开iframe" onclick="openIframe()" />
</body>
<script>
    // 跨域通信 https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage
    (function () {
        
    })()

    function initPostMessage(){
        var myFrame = document.getElementById("myFrameId")
        console.log("子iframe的src:", myFrame.attributes["src"].value)
        // 
        myFrame.onload = function () {
            var popup = myFrame.contentWindow;
            //iframe加载完立即发送一条消息
            popup.postMessage('刚加载iframe 就会发送此消息。。。', "http://127.0.0.1:8081/child.html");
            // 假设当前页面没有改变 location，这条语句会成功添加 message 到发送队列中去（targetOrigin 设置对了）
            popup.postMessage("hello there!", "http://127.0.0.1:8081/child.html");
        }
        //var popup = window.open("http://localhost:8081/child.html");
        

        function receiveMessage(event) {
            // 我们能相信信息的发送者吗？(也许这个发送者和我们最初打开的不是同一个页面).
            if (event.origin !== "http://127.0.0.1:8081"){
                return;
            }

            // event.source 是我们通过 window.open 打开的弹出页面 popup
            // event.data 是 popup 发送给当前页面的消息 "hi there yourself!  the secret response is: rheeeeet!"
            console.log("来自子iframe的消息:", event.data)
            if(event.data == "close"){
                myFrame.setAttribute("src", "")
            }
        }
        window.addEventListener("message", receiveMessage, false);
    }

    function openIframe(){
        var myFrame = document.getElementById("myFrameId")
        if(myFrame == null){
            var iframe = document.createElement("iframe")
            iframe.setAttribute("id", "myFrameId")
            iframe.setAttribute("name", "myFrame")
            iframe.setAttribute("src", "http://127.0.0.1:8081/child.html")
            document.body.appendChild(iframe)
        }

        initPostMessage()
    }

</script>

</html>